package io.sage.modules.employer.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;

import io.sage.annotation.Login;
import io.sage.annotation.LoginUser;
import io.sage.common.utils.CheckPassword;
import io.sage.common.utils.PageUtils;
import io.sage.common.utils.R;
import io.sage.common.validator.Assert;
import io.sage.common.validator.ValidatorUtils;
import io.sage.modules.employer.entity.Employer;
import io.sage.modules.employer.service.EmployerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @author xujh
 * @email jhang_mail@163.com
 * @date 2018-07-09 13:48:15
 */
@RestController
@RequestMapping("/sage/employer")
@Api(tags="员工接口")
public class EmployerController {
    @Autowired
    private EmployerService studentService;

	//设置APPID/AK/SK
	@Value(value = "${baidu.app.id}")
	private String APP_ID;
	@Value(value = "${baidu.api.key}")
	private String API_KEY ;
	@Value(value = "${baidu.secret.key}")
	private String SECRET_KEY ;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @ApiOperation("获取全部员工")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils selectStudentList = studentService.selectStudentList(params);
        return R.ok().put("page", selectStudentList);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @ApiOperation("根据id查询员工信息")
    public R info(@PathVariable("id") Integer id){
    	
        Employer student = studentService.selectByPrimaryKey(id);

        return R.ok().put("student", student);
    }
    
    /**
     * 信息
     */
    @Login
    @PostMapping("getStudentByUserId")
    @ApiOperation("获取个人中心数据")
    public R getStudentByUserId(@ApiIgnore @LoginUser Employer student){
    	
    	if(!StringUtils.isEmpty(student)){
    		//密码设置为空.
    		student.setUserPwd("");
    		return R.ok().put("data", student);
    		
    	}
    	return R.ok("没有获取到个人数据");
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody Employer student){
        ValidatorUtils.validateEntity(student);
        
        int update = studentService.updateByPrimaryKeySelective(student);//全部更新
        if(update>0){
        	return R.ok();
        }
        return R.error();
    }

    /**
     * 批量删除.
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
    	
        int delete = studentService.deleteBatchIds(ids);
        
        if(delete>0){
        	return R.ok();
        }
        
        return R.error();
    }
    
    
	/**
	 * 修改登录用户密码
	 */
    @Login
    @PostMapping("password")
	@ApiOperation("修改密码")
	public R password(@ApiIgnore @LoginUser Employer student , @RequestBody JSONObject jsonObject){
		
    	String userPwd = jsonObject.getString("userPwd");
    	String newUserPwd = jsonObject.getString("newUserPwd");
    	
    	
		Assert.isBlank(newUserPwd, "新密码不为能空");
		
		int updateByPrimaryKeySelective = studentService.updateBypwd(userPwd, newUserPwd,student);
		if(updateByPrimaryKeySelective>0){
			return R.ok();
		}
		
		return R.error("原密码不正确");
	}
    
    /**
	 * 修改登录用户密码
	 */
    @Login
    @PostMapping("resetPassword")
	@ApiOperation("修改密码")
	public R ResetPassword(@ApiIgnore @LoginUser Employer student , @RequestBody JSONObject jsonObject){
		
    	String userPwd = jsonObject.getString("userPwd");
    	String newUserPwd = jsonObject.getString("newUserPwd");
    	String resetPwd = jsonObject.getString("resetPwd");
    	
    	//校验参数.
    	if(StringUtils.isEmpty(userPwd)){
    				
    		return R.error("原始密码不能为空");
    	}
    	if(StringUtils.isEmpty(newUserPwd)){
    		
    		return R.error("新密码不能为空");
    	}
    	if(StringUtils.isEmpty(resetPwd)){
    		
    		return R.error("确认密码不能为空");
    	}
    	
    	if(!newUserPwd.equals(resetPwd)){
    		return R.error("两次密码不一样");
    	}
    	
		Assert.isBlank(newUserPwd, "新密码不为能空");
		Assert.isBlank(resetPwd, "密码确认不为能空");
		
		int updateByPrimaryKeySelective = studentService.updateBypwd(userPwd, newUserPwd,resetPwd,student);
		if(updateByPrimaryKeySelective>0){
			return R.ok();
		}
		
		return R.error("原密码不正确");
	}
    
    @RequestMapping("/uploadHeadPortrait")
    @ApiOperation("上传头像")
    public R uploadHeadPortrait(@ApiIgnore @LoginUser Employer student , MultipartFile file) {
    	String uploadHeadUrl = null ;
        try {
             uploadHeadUrl = studentService.uploadHeadPortrait(student,file);
        } catch (Exception e) {
            e.printStackTrace();
            R.error();
        }
		return R.ok().put("uploadHeadUrl", uploadHeadUrl);
    }
    
    @Login
    @PostMapping("updatePassWord")
    @ApiOperation("修改密码,小程序接口")
    public R updatePassWord(@RequestBody JSONObject jsonObject){
    	
    	String password = jsonObject.getString("password");
    	String newPassword = jsonObject.getString("newPassword");
    	String newPasswordConfirm = jsonObject.getString("newPasswordConfirm");
    	Integer userId = jsonObject.getInteger("userId");
    	if(userId==null){
    		return R.error("用户id不能为空");
    	}
    	//校验参数.
  	    if(StringUtils.isEmpty(password)|| password == null){
  		   return R.error("密码不能为空");
  	    }
  	    //校验参数.
  	    if(StringUtils.isEmpty(newPassword)|| newPassword == null){
  		   return R.error("新密码不能为空");
  	    }
  	    //校验参数.
  	    if(StringUtils.isEmpty(newPasswordConfirm)|| newPasswordConfirm == null){
  		   return R.error("确认密码不能为空");
  	    }
  	    //检测密码必须在6到12位，而且不能纯数字.
  	    boolean letterDigit = CheckPassword.isLetterDigit(newPassword);
  	    if(!letterDigit){
  	    	return R.error("密码必须为6-12位字母加数字组合");
  	    }
  	    
  	    if(!newPassword.equals(newPasswordConfirm)){
  	    	return R.error("两次输入放入密码不一致.");
  	    }
  	    
  	    Employer student = studentService.selectByPrimaryKey(userId);
  	    if(StringUtils.isEmpty(student)){
  	    	return R.error("修改密码失败");
  	    }
	    System.out.println(student.getUserPwd());
	    System.out.println(DigestUtils.sha256Hex(password));
  	    if(student.getUserPwd().equals(DigestUtils.sha256Hex(password))){
  	    	student.setUserPwd(DigestUtils.sha256Hex(newPassword));
  	    }else{
  	    	return R.error("原始密码不正确");
  	    }

  	    
		int update = studentService.updateByPrimaryKeySelective(student);//全部更新
		
		if(update>0){
			return R.ok();
		}else {
			return R.error();
		}
		
    }

	@RequestMapping()
	@ApiOperation("人脸验证")
	public R faceAuth(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){
		// 初始化一个AipFace
		AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

		// 可选：设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);

		String image1 = "";
				//"";
		String image2 = "";

		// image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
		MatchRequest req1 = new MatchRequest(image1, "BASE64");
		MatchRequest req2 = new MatchRequest(image2, "BASE64");
		ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
		requests.add(req1);
		requests.add(req2);

		org.json.JSONObject res = client.match(requests);
		System.out.println(res.toString(2));


		return R.ok();
	}

	public static void main(String[] args) {
		// 初始化一个AipFace
		AipFace client = new AipFace("16215862", "SLfcYnCHrZTBRyiC2cO6iSwO", "LFd1IOOKxfPKjGhLkQFz2Dfp6vLBnrdU");

		// 可选：设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);

		String image1 = GetImageStr("C:\\Users\\zxh\\Desktop\\1.jpg");
		String image2 = GetImageStr("C:\\Users\\zxh\\Desktop\\2.jpg");

		// image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
		MatchRequest req1 = new MatchRequest(image1, "BASE64");
		MatchRequest req2 = new MatchRequest(image2, "BASE64");
		ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
		requests.add(req1);
		requests.add(req2);

		org.json.JSONObject res = client.match(requests);
		System.out.println(res.toString(2));
	}
	public static String GetImageStr(String imgFile)
	{//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		//读取图片字节数组
		try
		{
			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		//对字节数组Base64编码
//		BASE64Encoder encoder = new BASE64Encoder();
//		return encoder.encode(data);//返回Base64编码过的字节数组字符串
		return null;
	}

}
